﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 销售订单服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class SalesordersService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Salesorders> _salesordersRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public SalesordersService(SqlSugarRepository<Salesorders> salesordersRep, ISqlSugarClient sqlSugarClient)
    {
        _salesordersRep = salesordersRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询销售订单 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询销售订单")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<SalesordersOutput>> Page(PageSalesordersInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _salesordersRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.BillNumber.Contains(input.Keyword) || u.DocumentStatus.Contains(input.Keyword) || u.Contact.Contains(input.Keyword) || u.ContactPhone.Contains(input.Keyword) || u.SalesGoods.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.BillNumber), u => u.BillNumber.Contains(input.BillNumber.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.DocumentStatus), u => u.DocumentStatus.Contains(input.DocumentStatus.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Contact), u => u.Contact.Contains(input.Contact.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ContactPhone), u => u.ContactPhone.Contains(input.ContactPhone.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.SalesGoods), u => u.SalesGoods.Contains(input.SalesGoods.Trim()))
            .WhereIF(input.SalesDateRange?.Length == 2, u => u.SalesDate >= input.SalesDateRange[0] && u.SalesDate <= input.SalesDateRange[1])
            .WhereIF(input.ClientName != null, u => u.ClientName == input.ClientName)
            .WhereIF(input.SalesDepartment != null, u => u.SalesDepartment == input.SalesDepartment)
            .WhereIF(input.SalesHead != null, u => u.SalesHead == input.SalesHead)
            .WhereIF(input.SalesQuantity != null, u => u.SalesQuantity == input.SalesQuantity)
            .WhereIF(input.SalesAmount != null, u => u.SalesAmount == input.SalesAmount)
            .WhereIF(input.Makeasingle != null, u => u.Makeasingle == input.Makeasingle)
            .WhereIF(input.Department != null, u => u.Department == input.Department)
            .WhereIF(input.MakeTimeRange?.Length == 2, u => u.MakeTime >= input.MakeTimeRange[0] && u.MakeTime <= input.MakeTimeRange[1])
            .WhereIF(input.Reviewers != null, u => u.Reviewers == input.Reviewers)
            .WhereIF(input.ReviewTimeRange?.Length == 2, u => u.ReviewTime >= input.ReviewTimeRange[0] && u.ReviewTime <= input.ReviewTimeRange[1])
            .LeftJoin<Customers>((u, clientName) => u.ClientName == clientName.Id)
            .LeftJoin<Customers>((u, clientName, salesDepartment) => u.SalesDepartment == salesDepartment.Id)
            .LeftJoin<Customers>((u, clientName, salesDepartment, salesHead) => u.SalesHead == salesHead.Id)
            .LeftJoin<Customers>((u, clientName, salesDepartment, salesHead, makeasingle) => u.Makeasingle == makeasingle.Id)
            .LeftJoin<department>((u, clientName, salesDepartment, salesHead, makeasingle, department) => u.Department == department.Id)
            .LeftJoin<Customers>((u, clientName, salesDepartment, salesHead, makeasingle, department, reviewers) => u.Reviewers == reviewers.Id)
            .Select((u, clientName, salesDepartment, salesHead, makeasingle, department, reviewers) => new SalesordersOutput
            {
                Id = u.Id,
                BillNumber = u.BillNumber,
                DocumentStatus = u.DocumentStatus,
                SalesDate = u.SalesDate,
                ClientName = u.ClientName,
                ClientNameFkDisplayName = $"{clientName.CustomerName}",
                Contact = u.Contact,
                ContactPhone = u.ContactPhone,
                SalesDepartment = u.SalesDepartment,
                SalesDepartmentFkDisplayName = $"{salesDepartment.SalesDepartments}",
                SalesHead = u.SalesHead,
                SalesHeadFkDisplayName = $"{salesHead.DirectorOfsales}",
                SalesQuantity = u.SalesQuantity,
                SalesAmount = u.SalesAmount,
                SalesGoods = u.SalesGoods,
                Makeasingle = u.Makeasingle,
                MakeasingleFkDisplayName = $"{makeasingle.Operator}",
                Department = u.Department,
                DepartmentFkDisplayName = $"{department.DepartmentName}",
                MakeTime = u.MakeTime,
                Reviewers = u.Reviewers,
                ReviewersFkDisplayName = $"{reviewers.Operator}",
                ReviewTime = u.ReviewTime,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取销售订单详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取销售订单详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Salesorders> Detail([FromQuery] QueryByIdSalesordersInput input)
    {
        return await _salesordersRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加销售订单 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加销售订单")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddSalesordersInput input)
    {
        var entity = input.Adapt<Salesorders>();
        return await _salesordersRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新销售订单 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新销售订单")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateSalesordersInput input)
    {
        var entity = input.Adapt<Salesorders>();
        await _salesordersRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除销售订单 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除销售订单")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteSalesordersInput input)
    {
        var entity = await _salesordersRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _salesordersRep.FakeDeleteAsync(entity);   //假删除
        //await _salesordersRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除销售订单 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除销售订单")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteSalesordersInput> input)
    {
        var exp = Expressionable.Create<Salesorders>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _salesordersRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _salesordersRep.FakeDeleteAsync(list);   //假删除
        //return await _salesordersRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataSalesordersInput input)
    {
        var clientNameData = await _salesordersRep.Context.Queryable<Customers>()
            .InnerJoinIF<Salesorders>(input.FromPage, (u, r) => u.Id == r.ClientName)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.CustomerName}"
            }).ToListAsync();
        var salesDepartmentData = await _salesordersRep.Context.Queryable<Customers>()
            .InnerJoinIF<Salesorders>(input.FromPage, (u, r) => u.Id == r.SalesDepartment)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.SalesDepartments}"
            }).ToListAsync();
        var salesHeadData = await _salesordersRep.Context.Queryable<Customers>()
            .InnerJoinIF<Salesorders>(input.FromPage, (u, r) => u.Id == r.SalesHead)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.DirectorOfsales}"
            }).ToListAsync();
        var makeasingleData = await _salesordersRep.Context.Queryable<Customers>()
            .InnerJoinIF<Salesorders>(input.FromPage, (u, r) => u.Id == r.Makeasingle)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.Operator}"
            }).ToListAsync();
        var departmentData = await _salesordersRep.Context.Queryable<department>()
            .InnerJoinIF<Salesorders>(input.FromPage, (u, r) => u.Id == r.Department)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.DepartmentName}"
            }).ToListAsync();
        var reviewersData = await _salesordersRep.Context.Queryable<Customers>()
            .InnerJoinIF<Salesorders>(input.FromPage, (u, r) => u.Id == r.Reviewers)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.Operator}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "clientName", clientNameData },
            { "salesDepartment", salesDepartmentData },
            { "salesHead", salesHeadData },
            { "makeasingle", makeasingleData },
            { "department", departmentData },
            { "reviewers", reviewersData },
        };
    }
    
    /// <summary>
    /// 导出销售订单记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出销售订单记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageSalesordersInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportSalesordersOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "销售订单导出记录");
    }
    
    /// <summary>
    /// 下载销售订单数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载销售订单数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportSalesordersOutput>(), "销售订单导入模板", (_, info) =>
        {
            if (nameof(ExportSalesordersOutput.ClientNameFkDisplayName) == info.Name) return _salesordersRep.Context.Queryable<Customers>().Select(u => $"{u.CustomerName}").Distinct().ToList();
            if (nameof(ExportSalesordersOutput.SalesDepartmentFkDisplayName) == info.Name) return _salesordersRep.Context.Queryable<Customers>().Select(u => $"{u.SalesDepartments}").Distinct().ToList();
            if (nameof(ExportSalesordersOutput.SalesHeadFkDisplayName) == info.Name) return _salesordersRep.Context.Queryable<Customers>().Select(u => $"{u.DirectorOfsales}").Distinct().ToList();
            if (nameof(ExportSalesordersOutput.MakeasingleFkDisplayName) == info.Name) return _salesordersRep.Context.Queryable<Customers>().Select(u => $"{u.Operator}").Distinct().ToList();
            if (nameof(ExportSalesordersOutput.DepartmentFkDisplayName) == info.Name) return _salesordersRep.Context.Queryable<department>().Select(u => $"{u.DepartmentName}").Distinct().ToList();
            if (nameof(ExportSalesordersOutput.ReviewersFkDisplayName) == info.Name) return _salesordersRep.Context.Queryable<Customers>().Select(u => $"{u.Operator}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入销售订单记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入销售订单记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportSalesordersInput, Salesorders>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 客户名称
                    var clientNameLabelList = pageItems.Where(x => x.ClientNameFkDisplayName != null).Select(x => x.ClientNameFkDisplayName).Distinct().ToList();
                    if (clientNameLabelList.Any()) {
                        var clientNameLinkMap = _salesordersRep.Context.Queryable<Customers>().Where(u => clientNameLabelList.Contains($"{u.CustomerName}")).ToList().ToDictionary(u => $"{u.CustomerName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.ClientName = clientNameLinkMap.GetValueOrDefault(e.ClientNameFkDisplayName ?? "");
                            if (e.ClientName == null) e.Error = "客户名称链接失败";
                        });
                    }
                    // 链接 销售部门
                    var salesDepartmentLabelList = pageItems.Where(x => x.SalesDepartmentFkDisplayName != null).Select(x => x.SalesDepartmentFkDisplayName).Distinct().ToList();
                    if (salesDepartmentLabelList.Any()) {
                        var salesDepartmentLinkMap = _salesordersRep.Context.Queryable<Customers>().Where(u => salesDepartmentLabelList.Contains($"{u.SalesDepartments}")).ToList().ToDictionary(u => $"{u.SalesDepartments}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.SalesDepartment = salesDepartmentLinkMap.GetValueOrDefault(e.SalesDepartmentFkDisplayName ?? "");
                            if (e.SalesDepartment == null) e.Error = "销售部门链接失败";
                        });
                    }
                    // 链接 销售负责人
                    var salesHeadLabelList = pageItems.Where(x => x.SalesHeadFkDisplayName != null).Select(x => x.SalesHeadFkDisplayName).Distinct().ToList();
                    if (salesHeadLabelList.Any()) {
                        var salesHeadLinkMap = _salesordersRep.Context.Queryable<Customers>().Where(u => salesHeadLabelList.Contains($"{u.DirectorOfsales}")).ToList().ToDictionary(u => $"{u.DirectorOfsales}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.SalesHead = salesHeadLinkMap.GetValueOrDefault(e.SalesHeadFkDisplayName ?? "");
                            if (e.SalesHead == null) e.Error = "销售负责人链接失败";
                        });
                    }
                    // 链接 制单人
                    var makeasingleLabelList = pageItems.Where(x => x.MakeasingleFkDisplayName != null).Select(x => x.MakeasingleFkDisplayName).Distinct().ToList();
                    if (makeasingleLabelList.Any()) {
                        var makeasingleLinkMap = _salesordersRep.Context.Queryable<Customers>().Where(u => makeasingleLabelList.Contains($"{u.Operator}")).ToList().ToDictionary(u => $"{u.Operator}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.Makeasingle = makeasingleLinkMap.GetValueOrDefault(e.MakeasingleFkDisplayName ?? "");
                            if (e.Makeasingle == null) e.Error = "制单人链接失败";
                        });
                    }
                    // 链接 所在部门
                    var departmentLabelList = pageItems.Where(x => x.DepartmentFkDisplayName != null).Select(x => x.DepartmentFkDisplayName).Distinct().ToList();
                    if (departmentLabelList.Any()) {
                        var departmentLinkMap = _salesordersRep.Context.Queryable<department>().Where(u => departmentLabelList.Contains($"{u.DepartmentName}")).ToList().ToDictionary(u => $"{u.DepartmentName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.Department = departmentLinkMap.GetValueOrDefault(e.DepartmentFkDisplayName ?? "");
                            if (e.Department == null) e.Error = "所在部门链接失败";
                        });
                    }
                    // 链接 审核人
                    var reviewersLabelList = pageItems.Where(x => x.ReviewersFkDisplayName != null).Select(x => x.ReviewersFkDisplayName).Distinct().ToList();
                    if (reviewersLabelList.Any()) {
                        var reviewersLinkMap = _salesordersRep.Context.Queryable<Customers>().Where(u => reviewersLabelList.Contains($"{u.Operator}")).ToList().ToDictionary(u => $"{u.Operator}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.Reviewers = reviewersLinkMap.GetValueOrDefault(e.ReviewersFkDisplayName ?? "");
                            if (e.Reviewers == null) e.Error = "审核人链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<Salesorders>>();
                    
                    var storageable = _salesordersRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.BillNumber?.Length > 32, "销售单号长度不能超过32个字符")
                        .SplitError(it => it.Item.DocumentStatus?.Length > 32, "单据状态长度不能超过32个字符")
                        .SplitError(it => it.Item.Contact?.Length > 32, "联系人长度不能超过32个字符")
                        .SplitError(it => it.Item.ContactPhone?.Length > 32, "联系方式长度不能超过32个字符")
                        .SplitError(it => it.Item.SalesGoods?.Length > 32, "销售货品长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
